const {
  Tool,
  API,
  Event,
  Storage
} = global.$util
Page({
  data: {
    showStage: false,
    mainFileList: [],
    detailFileList: [],
    title: '',
    goodsSkuVOList: [{
      skuName: '',
      skuNum: '',
      skuPfPrice: '',
      skuPrimeCost: '',
      skuSellingPrice: '',
    }],
    supplier: '111',
    shopId: Storage.getShopId(),
    titlePic: '',
    detailPic: '',
    prefix: "https://img.bajiaostar.com/"
  },
  // 页面初始化
  onLoad: function (options) {},
  // 滑动添加sku
  toAdd(event) {
    let item = event.currentTarget.dataset.item
    let result = Object.keys(item).every(value => item[value] !== '')
    if (!result) {
      wx.showToast({
        title: '请输入',
        icon: 'none',
        duration: 1500
      })
    } else {
      let param = {
        skuName: '',
        skuNum: '',
        skuPfPrice: '',
        skuPrimeCost: '',
        skuSellingPrice: '',
      }
      this.data.goodsSkuVOList.push(param)
      this.setData({
        goodsSkuVOList: this.data.goodsSkuVOList
      })
      this.selectComponent('#mySwipe').close()
    }
  },
  // 双向数据绑定
  changeFiledData(e) {
    let dataset = e.currentTarget.dataset
    let val = e.detail
    let newData = this.data.goodsSkuVOList
    newData[dataset.index][dataset.prop] = val;
    this.setData({
      goodsSkuVOList: newData
    })
  },
  // 
  addSure() {
    if (!this.data.color || !this.data.size || !this.data.price || !this.data.stock) return
    this.setData({
      showStage: false
    })
  },
  // 主图图片上传
  afterReadTitle(event) {
    const that = this
    const {
      file
    } = event.detail;
    that.setData({
      titlePic: ''
    });
    wx.showLoading({
      title: '上传中',
    });
    API['getQnToken']({}).then((res) => {
      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      wx.uploadFile({
        url: 'https://upload.qiniup.com', // 仅为示例，非真实的接口地址
        filePath: file.url,
        name: 'file',
        formData: {
          file: file.file,
          token: res.data.msg
        },
        success(res) {
          wx.hideLoading();
          if (res.statusCode === 200) {
            // 上传完成需要更新 fileList
            const {
              mainFileList = [],
                titlePic = ""
            } = that.data;
            mainFileList.push({
              ...file,
              url: that.data.prefix + JSON.parse(res.data).key
            });
            that.setData({
              mainFileList,
              titlePic: that.data.prefix + JSON.parse(res.data).key
            });
          } else {
            wx.showToast({
              title: '上传图片失败',
              icon: 'fail',
              duration: 1500
            })
          }
        },
      });
    }).catch(() => {
      wx.hideLoading();
      wx.showToast({
        title: '获取token失败',
        icon: 'fail',
        duration: 1500
      })
    })
  },
  // 删除主图
  deleteTitleImg() {
    this.setData({
      titlePic: '',
      mainFileList: []
    })
  },
  // 详情图片上传
  afterReadDetail(event) {
    const that = this
    const {
      file
    } = event.detail;
    wx.showLoading({
      title: '上传中',
    });
    API['getQnToken']({}).then((res) => {
      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      wx.uploadFile({
        url: 'https://upload.qiniup.com', // 仅为示例，非真实的接口地址
        filePath: file.url,
        name: 'file',
        formData: {
          file: file.file,
          token: res.data.msg
        },
        success(res) {
          wx.hideLoading();
          if (res.statusCode === 200) {
            // 上传完成需要更新 fileList
            const {
              detailFileList
            } = that.data;
            detailFileList.push({
              ...file,
              url: that.data.prefix + JSON.parse(res.data).key
            });
            that.setData({
              detailFileList
            });
          } else {
            wx.showToast({
              title: '上传图片失败',
              icon: 'fail',
              duration: 1500
            })
          }
        },
        fail() {
          wx.hideLoading();
          wx.showToast({
            title: '上传图片失败',
            icon: 'fail',
            duration: 1500
          })
        }
      });
    }).catch(() => {
      wx.hideLoading();
      wx.showToast({
        title: '获取token失败',
        icon: 'fail',
        duration: 1500
      })
    })
  },
  // 删除详情图
  deleteDetailImg(event) {
    const {
      index
    } = event.detail.index
    const {
      detailFileList
    } = this.data;
    detailFileList.splice(index, 1)
    this.setData({
      detailFileList
    });
  },
  // 提交
  submit() {
    const that = this
    if (that.data.mainFileList.length === 0) {
      wx.showToast({
        title: '请上传商品图片',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    if (that.data.detailFileList.length === 0) {
      wx.showToast({
        title: '请上传详情图片',
        icon: 'none',
        duration: 1500
      })
      return false;
    }
    that.setData({
      titlePic: that.data.mainFileList[0].url
    })
    that.data.detailFileList.forEach(
      item => {
        that.setData({
          detailPic: that.data.detailPic === '' ? item.url : that.data.detailPic + ',' + item.url
        })
      }
    )
    const params = {
      ...that.data,
    }
    API.addGoods(params).then(res => {
      Tool.switchTab('/pages/good/good')
    }).catch(err => {})
  }
})